大家好!今天的題目如果有刷題經驗的人相信都有寫過,因為它是Array系列的第一題。那就廢話不多說,直接上題目:
/*
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
Example 1:
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Output: Because nums[0] + nums[1] == 9, we return [0, 1].
Example 2:
Input: nums = [3,2,4], target = 6
Output: [1,2]
Example 3:
Input: nums = [3,3], target = 6
Output: [0,1]
*/
var twoSum = function(nums, target) {
};
這題會給一個數字陣列及目標值,我們希望能夠找到數字陣列中,哪兩個數字相加會與目標值相等,並回傳的兩個值在陣列中的位置。
思考:
var twoSum = function(nums, target) {
let result =[]
let num
let numIndex
}
var twoSum = function(nums, target) {
let result =[]
let num
let numIndex
for(let i = 0; i < nums.length; i++){
num = target - nums[i]
numIndex = nums.indexOf(num)
}
var twoSum = function(nums, target) {
let result = []
let numIndex
let num
for(let i = 0; i < nums.length; i++){
num = target - nums[i]
numIndex = nums.indexOf(num)
if(numIndex !== -1 ){
result = [i, numIndex]
break
}
}
return result
};
var twoSum = function(nums, target) {
let result = []
let numIndex
let num
for(let i = 0; i < nums.length; i++){
num = target - nums[i]
if(nums[i] === num){
nums[i] = undefined
}
numIndex = nums.indexOf(num)
if(numIndex !== -1 ){
result = [i, numIndex]
break
}
}
return result
};
以上是今天內容!寫法上有非常大的進步空間。如果有哪位大大路過經過,還請多多賜教。
我大神朋友簡單提供~
var twoSum = function (nums, target) {
for (let i = 0; i < nums.length; i++) {
for (let j = i + 1; j < nums.length; j++) {
if (nums[i] + nums[j] == target) return [i, j];
}
}
return '無符合';
};
console.log(twoSum([2, 7, 11, 15], 9));//[0,1]
console.log(twoSum([3, 2, 4], 6));//[1,2]
console.log(twoSum([3, 3], 6));//[0,1]
console.log(twoSum([1, 2, 3, 4], 10));//無符合
給你參考~~